package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        if (userSearchDto==null) {
            log.warn("参数为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String searchWords = userSearchDto.getSearchWords();
        if (StringUtils.isBlank(searchWords)) {
            log.warn("关键词为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int pageSize = userSearchDto.getPageSize();
        if(pageSize>20){
            pageSize=20;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("associateWords").regex((".*?"+searchWords+".*"))).limit(pageSize);
        List<ApAssociateWords> list = mongoTemplate.find(query, ApAssociateWords.class);
        return ResponseResult.okResult(list);
    }
}
